package com.yuanren.em.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanren.em.constants.Constants;
import com.yuanren.em.entity.Comment;
import com.yuanren.em.entity.Order;
import com.yuanren.em.exception.ServiceException;
import com.yuanren.em.mapper.CommentMapper;
import com.yuanren.em.mapper.OrderMapper;
import com.yuanren.em.utils.TokenUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class CommentService extends ServiceImpl<CommentMapper, Comment> {
    
    @Resource
    private CommentMapper commentMapper;
    
    @Resource
    private OrderMapper orderMapper;
    
    /**
     * 创建评论
     */
    @Transactional
    public void createComment(Comment comment) {
        // 获取当前用户ID
        Long currentUserId = (long) TokenUtils.getCurrentUser().getId();
        comment.setUserId(currentUserId);
        
        // 验证订单是否存在且属于当前用户
        LambdaQueryWrapper<Order> orderQueryWrapper = new LambdaQueryWrapper<>();
        orderQueryWrapper.eq(Order::getId, comment.getOrderId())
                        .eq(Order::getUserId, currentUserId);
        Order order = orderMapper.selectOne(orderQueryWrapper);
        
        if (order == null) {
            throw new ServiceException(Constants.CODE_500, "订单不存在或不属于当前用户");
        }
        
        // 验证订单状态是否为已收货
        if (!"已收货".equals(order.getState())) {
            throw new ServiceException(Constants.CODE_500, "只有已收货的订单才能评论");
        }
        
        // 检查是否已经评论过
        int existsCount = commentMapper.checkCommentExists(currentUserId, comment.getGoodId(), comment.getOrderId());
        if (existsCount > 0) {
            throw new ServiceException(Constants.CODE_500, "您已经对该商品进行过评论");
        }
        
        // 设置创建时间
        comment.setCreateTime(new Date());
        
        // 保存评论
        save(comment);
    }
    
    /**
     * 根据商品ID获取评论列表
     */
    public List<Comment> getCommentsByGoodId(Long goodId) {
        return commentMapper.selectCommentsByGoodId(goodId);
    }
    
    /**
     * 根据用户ID获取评论列表
     */
    public List<Comment> getCommentsByUserId(Long userId) {
        return commentMapper.selectCommentsByUserId(userId);
    }
    
    /**
     * 获取当前用户的评论列表
     */
    public List<Comment> getCurrentUserComments() {
        Long currentUserId = (long) TokenUtils.getCurrentUser().getId();
        return getCommentsByUserId(currentUserId);
    }
    
    /**
     * 检查用户是否已经评论过某个商品
     */
    public boolean hasCommented(Long userId, Long goodId, Long orderId) {
        int count = commentMapper.checkCommentExists(userId, goodId, orderId);
        return count > 0;
    }
    
    /**
     * 检查当前用户是否已经评论过某个商品
     */
    public boolean hasCurrentUserCommented(Long goodId, Long orderId) {
        Long currentUserId = (long) TokenUtils.getCurrentUser().getId();
        return hasCommented(currentUserId, goodId, orderId);
    }
    
    /**
     * 获取商品评论统计信息
     */
    public CommentMapper.CommentStatistics getCommentStatistics(Long goodId) {
        return commentMapper.getCommentStatistics(goodId);
    }
    
    /**
     * 分页获取评论（包含用户和商品信息）
     */
    public IPage<Comment> getCommentsPageWithInfo(int pageNum, int pageSize, String goodName, String userName, Integer rating) {
        IPage<Comment> page = new Page<>(pageNum, pageSize);
        return commentMapper.selectCommentsPageWithInfo(page, goodName, userName, rating);
    }
    
    /**
     * 商家回复评论
     */
    @Transactional
    public void replyComment(Long commentId, String replyContent) {
        Comment comment = getById(commentId);
        if (comment == null) {
            throw new ServiceException(Constants.CODE_500, "评论不存在");
        }
        
        comment.setReplyContent(replyContent);
        comment.setReplyTime(new Date());
        updateById(comment);
    }
    
    /**
     * 删除评论（仅管理员可用）
     */
    @Transactional
    public void deleteComment(Long commentId) {
        Comment comment = getById(commentId);
        if (comment == null) {
            throw new ServiceException(Constants.CODE_500, "评论不存在");
        }
        
        removeById(commentId);
    }
} 